#include "orderhistorywidget.h"
#include "errorhandler.h"
#include <QApplication>
#include <QStyle>
#include <QSplitter>
#include <QScrollBar>
#include <QFileDialog>
#include <QTextStream>
#include <QStandardPaths>

OrderHistoryWidget::OrderHistoryWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_mainSplitter(nullptr)
    , m_filterGroup(nullptr)
    , m_filterLayout(nullptr)
    , m_searchEdit(nullptr)
    , m_statusFilter(nullptr)
    , m_startDateEdit(nullptr)
    , m_endDateEdit(nullptr)
    , m_searchButton(nullptr)
    , m_resetButton(nullptr)
    , m_refreshButton(nullptr)
    , m_orderListWidget(nullptr)
    , m_orderListLayout(nullptr)
    , m_orderTable(nullptr)
    , m_orderCountLabel(nullptr)
    , m_loadingProgressBar(nullptr)
    , m_detailGroup(nullptr)
    , m_detailLayout(nullptr)
    , m_detailTextEdit(nullptr)
    , m_actionGroup(nullptr)
    , m_actionLayout(nullptr)
    , m_reorderButton(nullptr)
    , m_exportButton(nullptr)
    // , m_statusLabel(nullptr)  // 已删除状态标签
    , m_orderManager(nullptr)
    , m_isInitialized(false)
    , m_isLoading(false)
    , m_autoRefreshEnabled(true)
    , m_autoRefreshTimer(nullptr)
{
    // 获取OrderManager实例
    m_orderManager = &OrderManager::instance();
    
    // 创建自动刷新定时器
    m_autoRefreshTimer = new QTimer(this);
    m_autoRefreshTimer->setInterval(AUTO_REFRESH_INTERVAL_MS);
    connect(m_autoRefreshTimer, &QTimer::timeout, this, &OrderHistoryWidget::onAutoRefreshTimeout);
    
    // 初始化界面
    initializeUI();
    
    // 连接OrderManager信号
    connect(m_orderManager, &OrderManager::orderCreated, this, &OrderHistoryWidget::onOrdersUpdated);
    connect(m_orderManager, &OrderManager::orderStatusUpdated, this, &OrderHistoryWidget::onOrdersUpdated);
    connect(m_orderManager, &OrderManager::orderCompleted, this, &OrderHistoryWidget::onOrdersUpdated);
    
    m_isInitialized = true;
}

OrderHistoryWidget::~OrderHistoryWidget()
{
    // Qt会自动清理子对象
}

void OrderHistoryWidget::setUserId(const QString& userId)
{
    m_currentUserId = userId;
    
    // 清空当前数据
    clearData();
    
    // 如果有有效的用户ID，加载数据
    if (!userId.isEmpty()) {
        loadOrderData();
        
        // 启动自动刷新
        if (m_autoRefreshEnabled) {
            m_autoRefreshTimer->start();
        }
    } else {
        // 停止自动刷新
        m_autoRefreshTimer->stop();
    }
    
    updateUIState();
}

void OrderHistoryWidget::refreshOrders()
{
    if (m_currentUserId.isEmpty()) {
        return;
    }
    
    loadOrderData();
    showOperationResult("订单数据已刷新");
}

void OrderHistoryWidget::clearData()
{
    m_allOrders.clear();
    m_filteredOrders.clear();
    m_selectedOrder = Order();
    
    // 清空表格
    m_orderTable->setRowCount(0);
    
    // 清空详情
    clearOrderDetails();
    
    // 更新计数
    m_orderCountLabel->setText("订单总数: 0");
    
    updateUIState();
}

void OrderHistoryWidget::onOrdersUpdated()
{
    if (!m_currentUserId.isEmpty()) {
        // 使用短延迟确保数据已经完全保存，然后立即刷新
        QTimer::singleShot(50, this, [this]() {
            loadOrderData();
        });
    }
}

void OrderHistoryWidget::onOperationError(const QString& errorMessage)
{
    showOperationResult(errorMessage, false);
    m_isLoading = false;
    m_loadingProgressBar->setVisible(false);
    updateUIState();
}

void OrderHistoryWidget::onSearchButtonClicked()
{
    applyFilters();
}

void OrderHistoryWidget::onResetFilterClicked()
{
    // 重置筛选条件
    m_searchEdit->clear();
    m_statusFilter->setCurrentIndex(0); // "全部"
    m_startDateEdit->setDate(QDate::currentDate().addMonths(-1));
    m_endDateEdit->setDate(QDate::currentDate());
    
    // 重新应用筛选
    applyFilters();
}

void OrderHistoryWidget::onRefreshButtonClicked()
{
    refreshOrders();
}

void OrderHistoryWidget::onOrderSelectionChanged()
{
    int currentRow = m_orderTable->currentRow();
    if (currentRow >= 0 && currentRow < m_filteredOrders.size()) {
        m_selectedOrder = m_filteredOrders[currentRow];
        displayOrderDetails(m_selectedOrder);
    } else {
        m_selectedOrder = Order();
        clearOrderDetails();
    }
    
    updateUIState();
}

void OrderHistoryWidget::onOrderTableDoubleClicked(int row, int column)
{
    Q_UNUSED(column)
    
    if (row >= 0 && row < m_filteredOrders.size()) {
        Order order = m_filteredOrders[row];
        
        // 显示订单详细信息对话框
        QMessageBox detailDialog(this);
        detailDialog.setWindowTitle(QString("订单详情 - %1").arg(order.id));
        detailDialog.setText(createOrderDetailHTML(order));
        detailDialog.setTextFormat(Qt::RichText);
        detailDialog.setStandardButtons(QMessageBox::Ok);
        detailDialog.exec();
    }
}

void OrderHistoryWidget::onReorderButtonClicked()
{
    if (m_selectedOrder.id.isEmpty()) {
        showOperationResult("请先选择要重新下单的订单", false);
        return;
    }
    
    // 确认重新下单
    int ret = QMessageBox::question(this, "确认重新下单", 
                                   QString("确定要重新下单吗？\n订单ID: %1\n总金额: %2")
                                   .arg(m_selectedOrder.id)
                                   .arg(formatAmount(m_selectedOrder.totalAmount)),
                                   QMessageBox::Yes | QMessageBox::No,
                                   QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        emit reorderRequested(m_selectedOrder);
    }
}

void OrderHistoryWidget::onExportButtonClicked()
{
    if (m_filteredOrders.isEmpty()) {
        showOperationResult("没有可导出的订单数据", false);
        return;
    }
    
    // 选择保存文件（使用相对路径默认名）
    QString fileName = QFileDialog::getSaveFileName(this,
                                                   "导出订单历史",
                                                   QString("订单历史_%1.txt").arg(QDate::currentDate().toString("yyyyMMdd")),
                                                   "文本文件 (*.txt)");
    
    if (fileName.isEmpty()) {
        return;
    }
    
    // 导出数据
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        showOperationResult("无法创建导出文件", false);
        return;
    }
    
    QTextStream out(&file);
    out.setCodec("UTF-8");
    
    // 写入标题
    out << "餐厅订单系统 - 订单历史报告\n";
    out << "导出时间: " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << "\n";
    out << "用户ID: " << m_currentUserId << "\n";
    out << "订单总数: " << m_filteredOrders.size() << "\n";
    out << QString("=").repeated(60) << "\n\n";
    
    // 写入订单数据
    for (const Order& order : m_filteredOrders) {
        out << "订单ID: " << order.id << "\n";
        out << "创建时间: " << formatDateTime(order.createdDate) << "\n";
        out << "订单状态: " << formatOrderStatus(order.status) << "\n";
        out << "总金额: " << formatAmount(order.totalAmount) << "\n";
        out << "商品数量: " << order.items.size() << "\n";
        
        if (!order.items.isEmpty()) {
            out << "商品列表:\n";
            for (const OrderItem& item : order.items) {
                out << QString("  - %1 x %2 = %3\n")
                       .arg(item.menuItemName)
                       .arg(item.quantity)
                       .arg(formatAmount(item.price * item.quantity));
            }
        }
        
        out << QString("-").repeated(40) << "\n";
    }
    
    file.close();
    showOperationResult(QString("订单历史已导出到: %1").arg(fileName));
}

void OrderHistoryWidget::onStatusFilterChanged()
{
    applyFilters();
}

void OrderHistoryWidget::onDateFilterChanged()
{
    applyFilters();
}

void OrderHistoryWidget::onSearchTextChanged()
{
    // 延迟搜索，避免频繁筛选
    static QTimer* searchTimer = nullptr;
    if (!searchTimer) {
        searchTimer = new QTimer(this);
        searchTimer->setSingleShot(true);
        searchTimer->setInterval(500);
        connect(searchTimer, &QTimer::timeout, this, &OrderHistoryWidget::applyFilters);
    }
    
    searchTimer->start();
}

void OrderHistoryWidget::onAutoRefreshTimeout()
{
    if (!m_isLoading && !m_currentUserId.isEmpty()) {
        loadOrderData();
    }
}

void OrderHistoryWidget::initializeUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(10, 10, 10, 10);
    m_mainLayout->setSpacing(10);
    
    // 创建各个区域
    createFilterArea();
    
    // 创建主分割器
    m_mainSplitter = new QSplitter(Qt::Horizontal, this);
    
    createOrderListArea();
    createOrderDetailArea();
    
    // 设置分割器比例 (订单列表:详情 = 7:3)
    m_mainSplitter->addWidget(m_orderListWidget);
    m_mainSplitter->addWidget(m_detailGroup);
    m_mainSplitter->setStretchFactor(0, 7);
    m_mainSplitter->setStretchFactor(1, 3);
    
    m_mainLayout->addWidget(m_mainSplitter);
    
    createActionArea();
    
    // 状态标签已删除
    // m_statusLabel = new QLabel(this);
    // m_statusLabel->setAlignment(Qt::AlignCenter);
    // m_statusLabel->setVisible(false);
    // m_mainLayout->addWidget(m_statusLabel);
    
    // 应用样式
    applyStyleSheet();
    
    // 初始状态
    updateUIState();
}

void OrderHistoryWidget::createFilterArea()
{
    m_filterGroup = new QGroupBox("筛选条件", this);
    m_filterLayout = new QHBoxLayout(m_filterGroup);
    m_filterLayout->setSpacing(10);
    
    // 搜索框
    m_filterLayout->addWidget(new QLabel("搜索:", this));
    m_searchEdit = new QLineEdit(this);
    m_searchEdit->setPlaceholderText("输入订单ID或商品名称...");
    m_searchEdit->setMaximumWidth(200);
    connect(m_searchEdit, &QLineEdit::textChanged, this, &OrderHistoryWidget::onSearchTextChanged);
    m_filterLayout->addWidget(m_searchEdit);
    
    // 状态筛选
    m_filterLayout->addWidget(new QLabel("状态:", this));
    m_statusFilter = new QComboBox(this);
    m_statusFilter->addItem("全部", -1);
    m_statusFilter->addItem("待处理", static_cast<int>(OrderStatus::PENDING));
    m_statusFilter->addItem("制作中", static_cast<int>(OrderStatus::PREPARING));
    m_statusFilter->addItem("已完成", static_cast<int>(OrderStatus::COMPLETED));
    m_statusFilter->addItem("已取消", static_cast<int>(OrderStatus::CANCELLED));
    connect(m_statusFilter, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &OrderHistoryWidget::onStatusFilterChanged);
    m_filterLayout->addWidget(m_statusFilter);
    
    // 日期范围
    m_filterLayout->addWidget(new QLabel("开始日期:", this));
    m_startDateEdit = new QDateEdit(this);
    m_startDateEdit->setDate(QDate::currentDate().addMonths(-1));
    m_startDateEdit->setCalendarPopup(true);
    connect(m_startDateEdit, &QDateEdit::dateChanged, this, &OrderHistoryWidget::onDateFilterChanged);
    m_filterLayout->addWidget(m_startDateEdit);
    
    m_filterLayout->addWidget(new QLabel("结束日期:", this));
    m_endDateEdit = new QDateEdit(this);
    m_endDateEdit->setDate(QDate::currentDate());
    m_endDateEdit->setCalendarPopup(true);
    connect(m_endDateEdit, &QDateEdit::dateChanged, this, &OrderHistoryWidget::onDateFilterChanged);
    m_filterLayout->addWidget(m_endDateEdit);
    
    // 操作按钮
    m_searchButton = new QPushButton("搜索", this);
    m_searchButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogApplyButton));
    connect(m_searchButton, &QPushButton::clicked, this, &OrderHistoryWidget::onSearchButtonClicked);
    m_filterLayout->addWidget(m_searchButton);
    
    m_resetButton = new QPushButton("重置", this);
    m_resetButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogResetButton));
    connect(m_resetButton, &QPushButton::clicked, this, &OrderHistoryWidget::onResetFilterClicked);
    m_filterLayout->addWidget(m_resetButton);
    
    m_refreshButton = new QPushButton("刷新", this);
    m_refreshButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_BrowserReload));
    connect(m_refreshButton, &QPushButton::clicked, this, &OrderHistoryWidget::onRefreshButtonClicked);
    m_filterLayout->addWidget(m_refreshButton);
    
    // 添加弹性空间
    m_filterLayout->addStretch();
    
    m_mainLayout->addWidget(m_filterGroup);
}

void OrderHistoryWidget::createOrderListArea()
{
    m_orderListWidget = new QWidget();
    m_orderListLayout = new QVBoxLayout(m_orderListWidget);
    m_orderListLayout->setContentsMargins(0, 0, 0, 0);
    m_orderListLayout->setSpacing(5);
    
    // 订单计数标签
    m_orderCountLabel = new QLabel("订单总数: 0", m_orderListWidget);
    m_orderCountLabel->setStyleSheet("font-weight: bold; color: #333;");
    m_orderListLayout->addWidget(m_orderCountLabel);
    
    // 创建订单表格
    m_orderTable = new QTableWidget(m_orderListWidget);
    setupTableProperties();
    m_orderListLayout->addWidget(m_orderTable);
    
    // 加载进度条
    m_loadingProgressBar = new QProgressBar(m_orderListWidget);
    m_loadingProgressBar->setVisible(false);
    m_loadingProgressBar->setRange(0, 0); // 不确定进度
    m_orderListLayout->addWidget(m_loadingProgressBar);
}

void OrderHistoryWidget::createOrderDetailArea()
{
    m_detailGroup = new QGroupBox("订单详情", this);
    m_detailLayout = new QVBoxLayout(m_detailGroup);
    
    // 详情文本区域
    m_detailTextEdit = new QTextEdit(m_detailGroup);
    m_detailTextEdit->setReadOnly(true);
    m_detailTextEdit->setMaximumHeight(400);
    m_detailLayout->addWidget(m_detailTextEdit);
    
    clearOrderDetails();
}

void OrderHistoryWidget::createActionArea()
{
    m_actionGroup = new QGroupBox("操作", this);
    m_actionLayout = new QHBoxLayout(m_actionGroup);
    m_actionLayout->setSpacing(10);
    
    // 重新下单按钮
    m_reorderButton = new QPushButton("重新下单", this);
    m_reorderButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
    connect(m_reorderButton, &QPushButton::clicked, this, &OrderHistoryWidget::onReorderButtonClicked);
    m_actionLayout->addWidget(m_reorderButton);
    
    // 导出按钮
    m_exportButton = new QPushButton("导出历史", this);
    m_exportButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogSaveButton));
    connect(m_exportButton, &QPushButton::clicked, this, &OrderHistoryWidget::onExportButtonClicked);
    m_actionLayout->addWidget(m_exportButton);
    
    // 添加弹性空间
    m_actionLayout->addStretch();
    
    m_mainLayout->addWidget(m_actionGroup);
}

void OrderHistoryWidget::applyStyleSheet()
{
    // 为1024*600分辨率优化的样式
    setStyleSheet(R"(
        QGroupBox {
            font-size: 13px;
            font-weight: bold;
            color: #333;
            border: 2px solid #ddd;
            border-radius: 6px;
            margin-top: 8px;
            padding-top: 8px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 12px;
            padding: 0 6px 0 6px;
            background-color: white;
        }
        
        QTableWidget {
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
            alternate-background-color: #f9f9f9;
            selection-background-color: #e3f2fd;
            gridline-color: #e0e0e0;
            font-size: 12px;
        }
        
        QTableWidget::item {
            padding: 4px;
            border: none;
        }
        
        QTableWidget::item:selected {
            background-color: #2196F3;
            color: white;
        }
        
        QHeaderView::section {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            padding: 6px;
            font-weight: bold;
            font-size: 12px;
        }
        
        QLineEdit, QComboBox, QDateEdit {
            padding: 6px;
            border: 2px solid #ddd;
            border-radius: 4px;
            font-size: 12px;
            background-color: white;
        }
        
        QLineEdit:focus, QComboBox:focus, QDateEdit:focus {
            border-color: #4CAF50;
        }
        
        QPushButton {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            min-width: 70px;
        }
        
        QPushButton:hover {
            background-color: #2980B9;
        }
        
        QPushButton:pressed {
            background-color: #21618C;
        }
        
        #searchButton, #refreshButton {
            background-color: #2196F3;
            color: white;
        }
        
        #searchButton:hover, #refreshButton:hover {
            background-color: #1976D2;
        }
        
        #resetButton {
            background-color: #FF9800;
            color: white;
        }
        
        #resetButton:hover {
            background-color: #F57C00;
        }
        
        #reorderButton {
            background-color: #4CAF50;
            color: white;
        }
        
        #reorderButton:hover {
            background-color: #45a049;
        }
        
        #exportButton {
            background-color: #9C27B0;
            color: white;
        }
        
        #exportButton:hover {
            background-color: #7B1FA2;
        }
        
        QTextEdit {
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
            font-size: 12px;
            padding: 8px;
        }
        
        QProgressBar {
            border: 2px solid #ddd;
            border-radius: 4px;
            text-align: center;
            font-size: 12px;
        }
        
        QProgressBar::chunk {
            background-color: #4CAF50;
            border-radius: 2px;
        }
        
        .status-success {
            color: #4CAF50;
            font-weight: bold;
            background-color: #E8F5E8;
            padding: 6px;
            border-radius: 4px;
            border: 1px solid #4CAF50;
        }
        
        .status-error {
            color: #f44336;
            font-weight: bold;
            background-color: #FFEBEE;
            padding: 6px;
            border-radius: 4px;
            border: 1px solid #f44336;
        }
    )");
    
    // 设置按钮ID以应用特定样式
    m_searchButton->setObjectName("searchButton");
    m_resetButton->setObjectName("resetButton");
    m_refreshButton->setObjectName("refreshButton");
    m_reorderButton->setObjectName("reorderButton");
    m_exportButton->setObjectName("exportButton");
}

void OrderHistoryWidget::setupTableProperties()
{
    // 设置列数和列标题
    m_orderTable->setColumnCount(COL_COUNT);
    QStringList headers = {"订单ID", "创建时间", "状态", "总金额", "商品数量"};
    m_orderTable->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    m_orderTable->setAlternatingRowColors(true);
    m_orderTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_orderTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_orderTable->setSortingEnabled(true);
    m_orderTable->setShowGrid(true);
    
    // 设置列宽
    QHeaderView* header = m_orderTable->horizontalHeader();
    header->setStretchLastSection(true);
    m_orderTable->setColumnWidth(COL_ORDER_ID, 100);
    m_orderTable->setColumnWidth(COL_CREATE_TIME, 150);
    m_orderTable->setColumnWidth(COL_STATUS, 80);
    m_orderTable->setColumnWidth(COL_TOTAL_AMOUNT, 80);
    
    // 设置行高
    m_orderTable->verticalHeader()->setDefaultSectionSize(TABLE_ROW_HEIGHT);
    m_orderTable->verticalHeader()->setVisible(false);
    
    // 连接信号
    connect(m_orderTable, &QTableWidget::itemSelectionChanged, 
            this, &OrderHistoryWidget::onOrderSelectionChanged);
    connect(m_orderTable, &QTableWidget::cellDoubleClicked, 
            this, &OrderHistoryWidget::onOrderTableDoubleClicked);
}

void OrderHistoryWidget::loadOrderData()
{
    if (m_currentUserId.isEmpty()) {
        return;
    }
    
    m_isLoading = true;
    m_loadingProgressBar->setVisible(true);
    
    // 从OrderManager获取用户的所有订单
    m_allOrders = m_orderManager->getOrdersByCustomerId(m_currentUserId);
    
    // 应用筛选
    applyFilters();
    
    m_isLoading = false;
    m_loadingProgressBar->setVisible(false);
}

void OrderHistoryWidget::applyFilters()
{
    m_filteredOrders = filterOrders(m_allOrders);
    populateOrderTable(m_filteredOrders);
    
    // 更新计数
    m_orderCountLabel->setText(QString("订单总数: %1").arg(m_filteredOrders.size()));
    
    // 清空选择
    m_orderTable->clearSelection();
    clearOrderDetails();
    
    updateUIState();
}

void OrderHistoryWidget::populateOrderTable(const QList<Order>& orders)
{
    m_orderTable->setRowCount(orders.size());
    
    for (int row = 0; row < orders.size(); ++row) {
        const Order& order = orders[row];
        
        // 订单ID
        QTableWidgetItem* idItem = new QTableWidgetItem(order.id);
        idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
        m_orderTable->setItem(row, COL_ORDER_ID, idItem);
        
        // 创建时间
        QTableWidgetItem* timeItem = new QTableWidgetItem(formatDateTime(order.createdDate));
        timeItem->setFlags(timeItem->flags() & ~Qt::ItemIsEditable);
        m_orderTable->setItem(row, COL_CREATE_TIME, timeItem);
        
        // 状态
        QTableWidgetItem* statusItem = new QTableWidgetItem(formatOrderStatus(order.status));
        statusItem->setFlags(statusItem->flags() & ~Qt::ItemIsEditable);
        // 根据状态设置颜色
        switch (order.status) {
            case OrderStatus::PENDING:
                statusItem->setForeground(QBrush(QColor("#FF9800")));
                break;
            case OrderStatus::PREPARING:
                statusItem->setForeground(QBrush(QColor("#9C27B0")));
                break;
            case OrderStatus::COMPLETED:
                statusItem->setForeground(QBrush(QColor("#4CAF50")));
                break;
            case OrderStatus::CANCELLED:
                statusItem->setForeground(QBrush(QColor("#f44336")));
                break;
        }
        m_orderTable->setItem(row, COL_STATUS, statusItem);
        
        // 总金额
        QTableWidgetItem* amountItem = new QTableWidgetItem(formatAmount(order.totalAmount));
        amountItem->setFlags(amountItem->flags() & ~Qt::ItemIsEditable);
        amountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        m_orderTable->setItem(row, COL_TOTAL_AMOUNT, amountItem);
        
        // 商品数量
        QTableWidgetItem* countItem = new QTableWidgetItem(QString::number(order.items.size()));
        countItem->setFlags(countItem->flags() & ~Qt::ItemIsEditable);
        countItem->setTextAlignment(Qt::AlignCenter);
        m_orderTable->setItem(row, COL_ITEM_COUNT, countItem);
    }
}

void OrderHistoryWidget::displayOrderDetails(const Order& order)
{
    if (order.id.isEmpty()) {
        clearOrderDetails();
        return;
    }
    
    QString html = createOrderDetailHTML(order);
    m_detailTextEdit->setHtml(html);
}

void OrderHistoryWidget::clearOrderDetails()
{
    m_detailTextEdit->setHtml("<p style='color: #666; text-align: center; margin-top: 50px;'>"
                             "选择订单查看详情</p>");
}

void OrderHistoryWidget::updateUIState()
{
    bool hasValidUser = !m_currentUserId.isEmpty();
    bool hasSelection = !m_selectedOrder.id.isEmpty();
    bool hasOrders = !m_filteredOrders.isEmpty();
    
    // 启用/禁用控件
    m_filterGroup->setEnabled(hasValidUser);
    m_orderTable->setEnabled(hasValidUser);
    m_reorderButton->setEnabled(hasSelection);
    m_exportButton->setEnabled(hasOrders);
    
    // 状态标签已删除
    // if (!hasValidUser) {
    //     m_statusLabel->setText("请先选择用户");
    //     m_statusLabel->setProperty("class", "status-error");
    //     m_statusLabel->setVisible(true);
    // } else if (m_allOrders.isEmpty() && !m_isLoading) {
    //     m_statusLabel->setText("暂无订单记录");
    //     m_statusLabel->setProperty("class", "status-error");
    //     m_statusLabel->setVisible(true);
    // } else {
    //     m_statusLabel->setVisible(false);
    // }
}

void OrderHistoryWidget::showOperationResult(const QString& message, bool success)
{
    // 改为对话框弹出
    if (success) {
        QMessageBox::information(this, "操作成功", message);
    } else {
        QMessageBox::warning(this, "操作失败", message);
    }
}

QString OrderHistoryWidget::formatOrderStatus(OrderStatus status) const
{
    switch (status) {
        case OrderStatus::PENDING: return "待处理";
        case OrderStatus::PREPARING: return "制作中";
        case OrderStatus::COMPLETED: return "已完成";
        case OrderStatus::CANCELLED: return "已取消";
        default: return "未知";
    }
}

QString OrderHistoryWidget::formatAmount(double amount) const
{
    return QString("¥%1").arg(QString::number(amount, 'f', 2));
}

QString OrderHistoryWidget::formatDateTime(const QDateTime& dateTime) const
{
    if (!dateTime.isValid()) {
        return "未知";
    }
    return dateTime.toString("MM-dd hh:mm");
}

QList<Order> OrderHistoryWidget::filterOrders(const QList<Order>& orders) const
{
    QList<Order> filtered;
    
    QString searchText = m_searchEdit->text().trimmed().toLower();
    int statusFilter = m_statusFilter->currentData().toInt();
    QDate startDate = m_startDateEdit->date();
    QDate endDate = m_endDateEdit->date();
    
    for (const Order& order : orders) {
        // 文本搜索
        if (!searchText.isEmpty()) {
            bool textMatch = false;
            
            // 搜索订单ID
            if (order.id.toLower().contains(searchText)) {
                textMatch = true;
            }
            
            // 搜索商品名称
            if (!textMatch) {
                for (const OrderItem& item : order.items) {
                    if (item.menuItemName.toLower().contains(searchText)) {
                        textMatch = true;
                        break;
                    }
                }
            }
            
            if (!textMatch) {
                continue;
            }
        }
        
        // 状态筛选
        if (statusFilter >= 0 && static_cast<int>(order.status) != statusFilter) {
            continue;
        }
        
        // 日期筛选
        QDate orderDate = order.createdDate.date();
        if (orderDate < startDate || orderDate > endDate) {
            continue;
        }
        
        filtered.append(order);
    }
    
    return filtered;
}

Order OrderHistoryWidget::getSelectedOrder() const
{
    int currentRow = m_orderTable->currentRow();
    if (currentRow >= 0 && currentRow < m_filteredOrders.size()) {
        return m_filteredOrders[currentRow];
    }
    return Order();
}

QString OrderHistoryWidget::createOrderDetailHTML(const Order& order) const
{
    QString html = "<html><body style='font-family: Arial; font-size: 12px;'>";
    
    // 基本信息
    html += "<h3 style='color: #333; margin-bottom: 10px;'>订单信息</h3>";
    html += "<table style='width: 100%; border-collapse: collapse;'>";
    html += QString("<tr><td style='font-weight: bold; padding: 4px;'>订单ID:</td><td style='padding: 4px;'>%1</td></tr>").arg(order.id);
    html += QString("<tr><td style='font-weight: bold; padding: 4px;'>创建时间:</td><td style='padding: 4px;'>%1</td></tr>").arg(order.createdDate.toString("yyyy-MM-dd hh:mm:ss"));
    html += QString("<tr><td style='font-weight: bold; padding: 4px;'>订单状态:</td><td style='padding: 4px; color: %2;'>%1</td></tr>")
               .arg(formatOrderStatus(order.status))
               .arg(order.status == OrderStatus::COMPLETED ? "#4CAF50" : 
                    order.status == OrderStatus::CANCELLED ? "#f44336" : "#333");
    html += QString("<tr><td style='font-weight: bold; padding: 4px;'>总金额:</td><td style='padding: 4px; font-weight: bold; color: #4CAF50;'>%1</td></tr>").arg(formatAmount(order.totalAmount));
    html += "</table>";
    
    // 商品列表
    if (!order.items.isEmpty()) {
        html += "<h3 style='color: #333; margin-top: 15px; margin-bottom: 10px;'>商品详情</h3>";
        html += "<table style='width: 100%; border-collapse: collapse; border: 1px solid #ddd;'>";
        html += "<tr style='background-color: #f5f5f5;'>";
        html += "<th style='border: 1px solid #ddd; padding: 6px; text-align: left;'>商品名称</th>";
        html += "<th style='border: 1px solid #ddd; padding: 6px; text-align: center;'>数量</th>";
        html += "<th style='border: 1px solid #ddd; padding: 6px; text-align: right;'>单价</th>";
        html += "<th style='border: 1px solid #ddd; padding: 6px; text-align: right;'>小计</th>";
        html += "</tr>";
        
        for (const OrderItem& item : order.items) {
            html += "<tr>";
            html += QString("<td style='border: 1px solid #ddd; padding: 6px;'>%1</td>").arg(item.menuItemName);
            html += QString("<td style='border: 1px solid #ddd; padding: 6px; text-align: center;'>%1</td>").arg(item.quantity);
            html += QString("<td style='border: 1px solid #ddd; padding: 6px; text-align: right;'>%1</td>").arg(formatAmount(item.price));
            html += QString("<td style='border: 1px solid #ddd; padding: 6px; text-align: right;'>%1</td>").arg(formatAmount(item.price * item.quantity));
            html += "</tr>";
        }
        
        html += "</table>";
    }
    
    // 支付方式
    if (!order.paymentMethod.isEmpty()) {
        html += "<h3 style='color: #333; margin-top: 15px; margin-bottom: 10px;'>支付信息</h3>";
        html += QString("<p style='background-color: #f9f9f9; padding: 8px; border-radius: 4px; border: 1px solid #ddd;'>支付方式: %1</p>").arg(order.paymentMethod);
    }
    
    html += "</body></html>";
    return html;
}
